package acme.ws;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.map.ObjectMapper;

public class Util {

	public static final String UTF8 = "UTF-8";

	public static String convertStreamToString(InputStream is)
	throws IOException {
	/*
	* To convert the InputStream to String we use the
	* Reader.read(char[] buffer) method. We iterate until the
	* Reader return -1 which means there's no more data to
	* read. We use the StringWriter class to produce the string.
	*/
		if (is != null) {
			Writer writer = new StringWriter();
			 
			char[] buffer = new char[1024];
				try {
					Reader reader = new BufferedReader(new InputStreamReader(is, UTF8));
					int n;
					while ((n = reader.read(buffer)) != -1) {
					writer.write(buffer, 0, n);
				}
			} finally {
				if(is != null) is.close();
			}
		
			return writer.toString();
		} else {       
			return "";
		}
	
	}
	
	public static long getStreamLength(InputStream is) throws IOException{
		long size = 0;
		try{
			int data;
			while((data = is.read()) != -1){
				size ++;
			}
		}catch(IOException e){
			throw e;
		}finally{
			if(is != null) is.close();
		}
		return size;
	}
	
	public static void stream(InputStream in, OutputStream out){
		try {
	
			byte[] buffer = new byte[1024]; // Adjust if you want
			int bytesRead;
			while ((bytesRead = in.read(buffer)) != -1){
			    out.write(buffer, 0, bytesRead);
			}
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	
	public static String generateSignature(String apiKey, String apiSecret)
	throws IOException{
		// compute signature
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			throw new IOException("Unable to create signature.", e);
		}

		Charset charset = Charset.forName("UTF-8");
		md.update(apiKey.getBytes(charset));
		if (apiSecret != null)
			md.update(apiSecret.getBytes(charset));

		long ts = System.currentTimeMillis() / 1000L;
		md.update(String.valueOf(ts).getBytes(charset));
		String sig = String.format("%032x", new BigInteger(1, md.digest()));
		return sig;
	}
	public static void masheryAPICall(String url, String clientID, String areaID)
	{
		 try {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost postRequest = new HttpPost(url);
 
		String id = "1";
		String method = "oath2.fetchApplication";
		String serviceKey = "6zte9yufayv6agzm7u3epg2s";

		String apiKey = "yaa826zy4mswa33ytw6ynx3g";
		String apiSecret = "XGaEBwaqVY";
		String sig = generateSignature(apiKey,apiSecret);
		
		String jsonBody = "{\"id\": " + id 
				+ "\", \"jsonrpc\": \"2.0\", \"method\": \""+ method +
				"\", \"params\": {\"client\": { \"client_id\": \"" + clientID +
				"\"},\"service_key\": \"" + serviceKey + 
				"\",\"response_type\": null,\"uri\": null}}' 'https://api2.mashery.com/v2/json-rpc/" +
				areaID + "?apikey=" + apiKey + "&sig=" + sig;
		
		StringEntity input = new StringEntity(jsonBody);
		input.setContentType("application/json");
		postRequest.setEntity(input);
 
		HttpResponse response = httpClient.execute(postRequest);
 
		if (response.getStatusLine().getStatusCode() != 201) {
			throw new RuntimeException("Failed : HTTP error code : "
				+ response.getStatusLine().getStatusCode());
		}
 
		BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));
 
		String output;
		String jsonResponse = "";
		System.out.println("Output from Server .... \n");
		while ((output = br.readLine()) != null) {
			jsonResponse = jsonResponse + output;
		}
 
		
		HashMap<String,Object> result =
		        new ObjectMapper().readValue(jsonResponse, HashMap.class);
		
		String name = (String) result.get("name");
		
		httpClient.getConnectionManager().shutdown();
 
	  } catch (MalformedURLException e) {
 
		e.printStackTrace();
 
	  } catch (IOException e) {
 
		e.printStackTrace();
 
	  }
 
	}

	}

